/**
 * Created by zhoue on 2018/12/26.
 */
window.onresize=function (event) {
    //随屏幕自适应map内容div的高度
    /*var HEAD_HEIGHT = 65;
    var pheight = document.documentElement.clientHeight;
    var currentHeight = Number(pheight)-HEAD_HEIGHT-5;

    var mapContent = document.getElementById("parentMapContainer");
    //mapContent.clientHeight = currentHeight + "px";
    mapContent.style.height = currentHeight + "px";*/
    var testContent = document.getElementById("test-pie-area");
    var testChart = echarts.getInstanceByDom(testContent);
    testChart.resize();

    var testBarContent = document.getElementById("test-bar");
    var curBarechart = echarts.getInstanceByDom(testBarContent);
    curBarechart.resize();

    var testLineContent = document.getElementById("test-line");
    var curLineechart = echarts.getInstanceByDom(testLineContent);
    curLineechart.resize();
}

window.onload=function (event) {
    //设置map内容div的初始高度
    /*var HEAD_HEIGHT = 65;
    var pheight = document.documentElement.clientHeight;
    var currentHeight = Number(pheight)-HEAD_HEIGHT-5;
    var pmapContent = document.getElementById("parentMapContainer");
    pmapContent.style.height = currentHeight + "px";

    var riskManageBody = document.getElementById("risk-manage-body");
    riskManageBody.style.height = (currentHeight-45) + "px";*/

    //初始化时钟
    var datavtimeElement = document.getElementById("datav-time");
    var startTime = new Date();
    var startTimestr = startTime.toLocaleString();
    setInterval(function () {
        var currentTime = new Date();
        datavtimeElement.innerHTML = currentTime.toLocaleString();
    }, 1000)
    datavtimeElement.innerHTML = startTimestr;

    InitMapContent();
    InitPieAreaContent()
    InitBarContent();
    InitLineContent()
}

//自定义方法
function InitMapContent() {
    var map = L.map('mapContainer');
    var baseLayers = {
        "高德地图": L.tileLayer('http://webrd0{s}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}', {
            subdomains: "1234"
        }),
        '高德影像': L.layerGroup([L.tileLayer('http://webst0{s}.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}', {
            subdomains: "1234"
        }), L.tileLayer('http://t{s}.tianditu.cn/DataServer?T=cta_w&X={x}&Y={y}&L={z}', {
            subdomains: "1234"
        })]),
        'GeoQ灰色底图': L.tileLayer('http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}').addTo(map)
    };
    L.tileLayer('https://a.tiles.mapbox.com/v3/foursquare.map-0y1jh28j/{z}/{x}/{y}.png', {
        attribution: 'Map &copy; Pacific Rim Coordination Center (PRCC).  Certain data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>',
        key: 'BC9A493B41014CAABB98F0471D759707',
        styleId: 22677
    });

    var layercontrol = L.control.layers(baseLayers,{}, {
        position: "topright"
    }).addTo(map);
    map.setView(L.latLng(37.550339, 104.114129), 4);
    var overlay = new L.echartsLayer3(map, echarts);
    var chartsContainer = overlay.getEchartsContainer();
    var myChart = overlay.initECharts(chartsContainer);

    var data = mapProjectData.data;
    var geoCoordMap = mapProjectData.geoData;

    var convertData = function (data) {
        var res = [];
        for (var i = 0; i < data.length; i++) {
            var geoCoord = geoCoordMap[data[i].name];
            if (geoCoord) {
                res.push({
                    name: data[i].name,
                    value: geoCoord.concat(data[i].value)
                });
            }
        }
        return res;
    };

    var option = {
        // backgroundColor: '#404a59',
        title: {
            text: '中建三局总承包公司建筑项目分布图',
            subtext: '',
            sublink: '',
            left: 'center',
            textStyle: {
                color: '#fff'
            }
        },
        tooltip : {
            trigger: 'item'
        },
        legend: {
            orient: 'vertical',
            y: 'bottom',
            x:'right',
            data:['项目分布'],
            textStyle: {
                color: '#fff'
            }
        },
        geo: {
            map: '',
            label: {
                emphasis: {
                    show: false
                }
            },
            roam: true,
            itemStyle: {
                normal: {
                    areaColor: '#323c48',
                    borderColor: '#111'
                },
                emphasis: {
                    areaColor: '#2a333d'
                }
            }
        },
        series : [
            {
                name: '项目分布',
                type: 'scatter',
                coordinateSystem: 'geo',
                data: convertData(data),
                symbolSize: function (val) {
                    return val[2] / 10;
                },
                label: {
                    normal: {
                        formatter: '{b}',
                        position: 'right',
                        show: false
                    },
                    emphasis: {
                        show: true
                    }
                },
                itemStyle: {
                    normal: {
                        color: '#ddb926'
                    }
                }
            },
            {
                name: 'Top 5',
                type: 'effectScatter',
                coordinateSystem: 'geo',
                data: convertData(data.sort(function (a, b) {
                    return b.value - a.value;
                }).slice(0, 6)),
                symbolSize: function (val) {
                    return val[2] / 10;
                },
                showEffectOn: 'render',
                rippleEffect: {
                    brushType: 'stroke'
                },
                hoverAnimation: true,
                label: {
                    normal: {
                        formatter: '{b}',
                        position: 'right',
                        show: true
                    }
                },
                itemStyle: {
                    normal: {
                        color: '#f4e925',
                        shadowBlur: 10,
                        shadowColor: '#333'
                    }
                },
                zlevel: 1
            }
        ]
    };
    // 使用刚指定的配置项和数据显示图表。
    overlay.setOption(option);
    overlay.getECharts().on('click', function(params) {
        //alert("名称：" + params.name + "值：" + params.value.join());
        changeDataSource();
    });
}

function InitPieAreaContent() {
    var testContent = document.getElementById("test-pie-area");
    var testChart = echarts.init(testContent, 'dark');
    var option = {
        title: {},
        tooltip : {
            trigger: 'item',
            formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        series : [
            {
                name:'访问来源',
                type:'pie',
                radius : '70%',
                center: ['50%', '50%'],
                data:[
                    {value:335, name:'直接访问'},
                    {value:310, name:'邮件营销'},
                    {value:274, name:'联盟广告'},
                    {value:235, name:'视频广告'},
                    {value:400, name:'搜索引擎'}
                ].sort(function (a, b) { return a.value - b.value; }),
                roseType: 'radius',
                label: {
                    normal: {
                        textStyle: {
                            color: 'rgba(255, 255, 255, 0.3)'
                        }
                    }
                },
                labelLine: {
                    normal: {
                        lineStyle: {
                            color: 'rgba(255, 255, 255, 0.3)'
                        },
                        smooth: 0.2,
                        length: 1,
                        length2: 5
                    }
                },
            }
        ]
    };
    testChart.setOption(option);
}

function InitBarContent() {
    var testBarContent = document.getElementById("test-bar");
    var testBarChart = echarts.init(testBarContent, 'dark');
    var option = {
        tooltip : {},
        legend: { show:false, },    //data数组不设置，legend不展示
        //设置图形的展示大小
        grid: {
            width: '100%',
            height: 108,
            top: 5,
            left: '0',
            right: '0',
            bootom: '0',
            containLabel: true  //y轴备注文字
        },
        toolbox: { show : false, },
        xAxis : {
            type : 'value',
            splitLine: {show: false}    //去除背景栅格
        },
        yAxis : {
            show: true,
            type: 'category',
            splitLine: {show: false},
            data : ['华北', '山东','中原','中南','华南']
        },
        series : [
            {
                name:'已完成',
                type:'bar',
                stack: '总量',    //设置bar叠加
                barCategoryGap: 6,
                //设置内部数值
                // itemStyle : {
                //     barBorderRadius: 10,
                //     normal: {
                //         label : {show: true, position: 'insideLeft'}
                //     }
                // },
                data:[450, 712, 511, 354, 890]
            },
            {
                name:'未完成',
                type:'bar',
                stack: '总量',
                barCategoryGap: 6,
                data:[820, 832, 901, 934, 1290]
            }
        ]
    };
    testBarChart.setOption(option);
}

function InitLineContent() {
    var testLineContent = document.getElementById("test-line");
    var testLineChart = echarts.init(testLineContent, 'dark');
    var option = {
        grid: {
            width: '100%',
            height: 108,
            top: 10,
            left: '0',
            right: '0',
            bootom: '0',
            containLabel: true  //y轴备注文字
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            splitLine: {show: false},
            data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
        },
        yAxis: {
            type: 'value',
            splitLine: {show: false},
        },
        series: [{
            data: [820, 932, 901, 934, 1290, 1330, 1320, 566, 423, 774,2220,2999],
            type: 'line',
            areaStyle: {
                opacity: 0.5,
            }
        }]
    };
    testLineChart.setOption(option);
}

function changeDataSource(){
    var testPieAreaContent = document.getElementById("test-pie-area");
    var curPieAreaechart = echarts.getInstanceByDom(testPieAreaContent);
    var pienames = ['基础设施', '房建', '海外', '其他'];
    var pieareaarr = [];
    while(pieareaarr.length<4){
        var randomvalue1 = Math.random()*(100-40)+40;    //生成40到100之间的随机数
        pieareaarr.push(Math.round(randomvalue1));
    }
    var color=['#00cfff','#006ced','#ffe000','#ffa800'];
    var pieareaarr1 = pieareaarr.map(function(value, idx, arr){
        return {
            value: value,
            name: pienames[idx],
            itemStyle: {
                normal: {
                    borderWidth: 0,
                    shadowBlur: 10,
                    borderColor: color[idx],
                    shadowColor: color[idx]
                }
            }
        };
    })
    var peiareaoption = getEchartsOption.getPieAreaOption({
        data:pieareaarr1
    });
    curPieAreaechart.setOption(peiareaoption, true);


    var testBarContent = document.getElementById("test-bar");
    var curBarechart = echarts.getInstanceByDom(testBarContent);
    var cdarr = [], rdarr=[];
    while(cdarr.length<5 || rdarr.length<5){
        var randomvalue1 = Math.random()*(1000-300)+300;    //生成40到100之间的随机数
        cdarr.push(Math.round(randomvalue1));
        var randomvalue2 = Math.random()*(500-100)+100;    //生成40到100之间的随机数
        rdarr.push(Math.round(randomvalue2));
    }
    var baroption = getEchartsOption.getBarOption({
        completedata: cdarr,
        remaindata: rdarr
    });
    curBarechart.setOption(baroption, true);

    var testLineContent = document.getElementById("test-line");
    var curLineechart = echarts.getInstanceByDom(testLineContent);
    var linearr = [];
    while(linearr.length<10){
        var randomvalue2 = Math.random()*(100-20)+20;    //生成20到80之间的随机数
        linearr.push(Math.round(randomvalue2));
    }
    var Lineoption = getEchartsOption.getLineOption({
        data: linearr,
    });
    curLineechart.setOption(Lineoption, true);
}